<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>photo</title>
    <style>
        body {
            background: #212f3d;
            max-width: 1100px;
            margin: auto;
            padding: 6px;
            /*border: 1px solid lightgrey;*/
            color: whitesmoke;
        }

        a {
            color: whitesmoke;
        }

        .collect button {
            border: none;
            background: none;
            cursor: pointer;
            outline: none;
            display: flex;
            align-items: center;
            margin: auto;
        }

        .collected path {
            fill: red;
        }

        img {
            width: 500px;
            margin: auto;
            display: block;
        }

        /*    媒体查询 */
        @media screen and (max-width: 600px) {
            img {
                width: 90%;
            }
        }


    </style>
</head>
<body>
<div th:replace="~{common-page/header.html :: myheader}"></div>

<!--<p><span th:text="${views}"></span> 次浏览 </p>-->

<div style="text-align: center;  margin-bottom: 15px; ">
    <h1 th:text="${title}"></h1>
    <h3 th:text="${description}" style="opacity: 0.6;"></h3>
    <p> 价格 <span th:text="${price}" style="font-size: larger; font-weight: bolder; color: red;"></span> 元 </p>
    <a href="#" style="font-size: larger; text-decoration: none; font-weight: bolder; border: 2px solid lightgray; padding: 8px;" onclick="buy()">下载</a>
    <p>尊敬的用户: 支付成功后需要再次点击一次下载按钮, 才能下载高清图片</p>
    <div id="photo-netdistURL"></div>
</div>

<div th:each="obj,iterStat:${img_path}">
    <img th:src="'/images/Photo/'+${obj}">
    <p></p>
    <!--    <p th:text="${obj}" ></p>-->
</div>

<div class="collect ">
    <button onclick="collect()">
        <?xml version="1.0" encoding="UTF-8"?>
        <svg width="33" height="33" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg" id="collect-svg" class="">
            <path d="M23.9986 5L17.8856 17.4776L4 19.4911L14.0589 29.3251L11.6544 43L23.9986 36.4192L36.3454 43L33.9586 29.3251L44 19.4911L30.1913 17.4776L23.9986 5Z" fill="none" stroke="#dfcfcf" stroke-width="4" stroke-linejoin="round"/>
        </svg>
        <span style="font-size: 24px; color: whitesmoke;" th:text="${collect}" id="collect_count"></span>
    </button>
</div>

<br><br><br><br><br><br>

<br><br><br><br><br><br>
</body>
<script src="/static/js/common-plugin/custom-modal.js"></script>
<script th:inline="javascript">


    let usernameByCookie = [[${usernameByCookie}]];
    console.log(usernameByCookie);

    let photo_id = [[${id}]];
    console.log(photo_id);


    function collect() {
        if (usernameByCookie === null) {
            let template = `
                <div class="container"  style="color: black; ">
                   <h3>亲, 你好像没有登录?</h3>
                   <h3>需要先登录才能收藏哦~</h3>
                </div>  `;
            custom_modal(template,
                function () {
                },
                function () {
                }
            );
            return false;
        }
        fetch(`/api/collect/toggle?username=${usernameByCookie}&photo_id=${photo_id}`, {method: 'POST'})
            .then(response => response.text())  // 解析响应体为文本
            .then((data) => {
                console.log(data)
                // alert("收藏成功");
                let collect_svg = document.getElementById("collect-svg")
                collect_svg.classList.toggle("collected")
                document.getElementById("collect_count").innerText = data;
            })
            .catch(() => {
                alert("收藏失败");
            });
    }

    document.addEventListener('DOMContentLoaded', () => {
        isCollect();
    });

    async function isCollect() {
        await fetch(`/api/collect/isCollect?username=${usernameByCookie}&photo_id=${photo_id}`, {method: 'POST'})
            .then(response => response.text())  // 解析响应体为文本
            .then((data) => {
                console.log(data)
                let collect_svg = document.getElementById("collect-svg");
                if (data === "false") {
                    collect_svg.classList.remove("collected");
                }
                if (data === "true") {
                    collect_svg.classList.add("collected");
                }
            })
            .catch(() => {
                alert("收藏失败");
            });
    }


    // 判断是否已经购买
    function is_buy(username) {
        console.log("is_buy......");
        let api_url = "/api/is_buy";
        let postObj = {
            id: photo_id,
            username: username
        };
        return fetch(api_url, {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(postObj),
        })
            .then(response => response.text())  // 解析响应为文本
            .then(data => {
                return data;  // 返回 data，供外部使用
                // 已经购买:  https://pan.baidu.com/s/xxxxxxxxxx
                // 没购买: not_paid
            })
            .catch((error) => {
                console.error('Error:', error);
                return "error";  // 捕获错误并返回 "error"
            });
    }


    // 还没有支付
    function not_paid_buy() {
        console.log(usernameByCookie)
        //   判断是否登录
        if (usernameByCookie === null) {
            // 没有登录 , 无登录购买
            let template = `
                <div class="container"  style="color: black; ">
                   <h3>亲, 你好像没有登录?</h3>
                   <h1>不过没有登录也是可以直接购买的</h1>
                   <h3>但是我们还是推荐你登录后购买, 这样可以保留购买记录</h3>
                   <h2>是否进行 无登录购买 ? </h2>
                </div>  `;
            custom_modal(template,
                function () {
                    console.log("YES");
                    let temUsername = userIdentifier;  // 随机分配一个 username
                    go_to_pay_page(temUsername);
                },
                function () {
                    console.log("NO");
                }
            );
            return false;
        } else {
            // 已经登录 , 登录购买
            let template = `
                <div class="container"  style="color: black; ">
                   <h3>亲, 你已经登录 !  </h3>
                   <h1>请问现在支付购买吗 ? </h1>
                </div>  `;
            custom_modal(template,
                function () {
                    console.log("YES");
                    // let temUsername = userIdentifier;  // 随机分配一个 username
                    go_to_pay_page(usernameByCookie);
                },
                function () {
                    console.log("NO");
                }
            );
            return false;
        }
    }

    function buy() {
        let tempUsername = null;
        if (usernameByCookie === null) {
            tempUsername = userIdentifier;
        } else {
            tempUsername = usernameByCookie;
        }
        // 先判断是否已经购买
        is_buy(tempUsername).then(data => {
            console.log("返回的数据:", data);
            // 是否包含 pan.baidu.com
            if (data.includes("pan.baidu.com")) {
                document.getElementById("photo-netdistURL").innerHTML = `<a href="${data}"  target="_blank">${data}</a>`;
                return false;
            }
            if (data === "not_paid") {
                not_paid_buy()
            }
        });
    }

    // 前往支付
    function go_to_pay_page(username){
        let api_url = "/api/buy";
        let postObj = {
            id: photo_id,
            username: username
        };
        fetch(api_url, {
            method: 'POST',
            headers: {'Content-Type': 'application/json',},
            body: JSON.stringify(postObj),   // GET 请求不需要 body
        })
            // .then(response => response.json())  // 解析响应为 json, 无需再 JSON.parse() 解析
            .then(response => response.text())  // 解析响应为 文本
            .then(data => {
                if (data === "error") {
                    alert("抱歉, 出错了...")
                } else {
                    console.log(data)
                    // 是否同时包含
                    if (data.includes("url_qrcode") && data.includes("success")) {
                        // 说明还没有支付
                        let resp = JSON.parse(data);
                        let url = resp.url;
                        console.log(url)
                        window.location.href = url;
                        return false;
                    }
                    alert("抱歉, 出错了...");
                }
            })
            .catch((error) => {
                console.error('Error:', error);
            });
    }


    function generateUserIdentifier() {
        // 获取用户的硬件、操作系统、浏览器信息
        const platform = navigator.platform; // 操作系统信息
        const userAgent = navigator.userAgent; // 浏览器信息
        const hardwareConcurrency = navigator.hardwareConcurrency || 'unknown'; // CPU 核心数

        // 将信息组合成一个字符串
        const deviceInfo = `${platform}-${userAgent}-${hardwareConcurrency}`;

        // 将设备信息转换为一个哈希值
        let hash = 0;
        for (let i = 0; i < deviceInfo.length; i++) {
            const char = deviceInfo.charCodeAt(i);
            hash = (hash << 5) - hash + char;
            hash |= 0; // 将 hash 值转换为 32 位整数
        }

        // 返回唯一的用户标识符，基于设备和浏览器信息
        let userIdentifier = hash.toString(24);
        userIdentifier = userIdentifier.replace(/-/g, '');
        return userIdentifier;
    }

    // 根据硬件设备信息 , 和浏览器信息生成唯一的用户标识符 , 来识别用户
    const userIdentifier = generateUserIdentifier();
    // alert(userIdentifier);


</script>
</html>